/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const redis = require('../../util/redis');
const logger = require('../../util/logger');
const { isProd } = require('../../util');

module.exports = class {
  
  constructor(options) {
    this._options = Object.assign({
      election: 10000,
      namespace: 'ss-koa'
    }, options);
    if (!isProd()) {
      this._options.namespace = this.options.namespace + ':' + require('os').hostname();
    }
    this._node = this._options.namespace + ':node:' + options.uuid;
    this._masterKey = this._options.namespace + ':master';
    this._master = false;
    this._election();
  }
  
  get isMaster() {
    return this._master;
  }
  
  _election() {
    redis.ops().deleteNoTtl(this._masterKey, (err) => logger.error(err));
    setInterval(() => {
      redis.ops().lock(this._masterKey, this._node, this._options.election + 5000)
        .then(success => {
          this._master = success;
        }).catch(err => logger.error(err));
    }, this._options.election);
  }
  
};
